<?php
/**
 * 媒资管理服务层
 */

namespace app\admin\service;

use app\model\Applet;
use app\model\EpisodeAuditRecords;
use app\model\ThirdVideos;
use app\model\VideoAuditRecords;
use app\model\VideoDetails;
use app\model\Videos;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Queue;

class MediaAssetService
{

    public $videoModel;
    public $detailModel;
    public $thirdVideoModel;

    public function __construct(ThirdVideos $thirdVideos, Videos $videos, VideoDetails $details)
    {
        $this->thirdVideoModel = $thirdVideos;
        $this->videoModel = $videos;
        $this->detailModel = $details;
    }

    //加入第三方媒资管理库
    public function addThirdPartyVideo(array $params)
    {
        $video = $this->videoModel->getInfoById($params['video_id'], 'id,name,cover_img,sylloge,synopsis');
        if (!$video) return ['参数错误', 400];

        $is_exist = $this->thirdVideoModel->getOneByWhere([
            'platform' => $params['type'],
            'video_id' => $video['id'],
        ]);
        if ($is_exist) return ['该投放平台已添加该短剧'];

        ThirdVideos::create([
            'video_id' => $video['id'],
            'platform' => $params['type'],
        ]);

        return [];
    }

    //微信平台媒资短剧列表
    public function wxList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [['is_delete', '=', 0], ['is_copy', '=', 0], ['original_id','=', 0]];
        $query = Videos::alias('v')
            ->join('third_videos t', 't.video_id = v.id and platform = 1', 'left')
            ->field('t.id,t.platform,t.is_authorize,t.applet_ids,v.id as video_id,v.name,v.cover_img,v.is_shelves,v.sylloge,v.drama_id')
            ->where($where);

        if (!empty($params['name'])) $query->where('v.name','like', '%' . $params['name'] . '%');

        if (!empty($params['video_id'])) $query->where('v.id', $params['video_id']);

        $total = $query->count();
        $order = 'v.sort desc, v.id desc, v.give_count desc';
        $lists = $query->order($order)->page($page, $limit)->select()->toArray();

        foreach ($lists as &$list) {
            $list['id'] = $list['id'] ?: 0;
            $list['platform'] = 1;
            $list['is_authorize'] = $list['is_authorize'] ?: 0;
            $list['applet_ids'] = $list['applet_ids'] ? json_decode($list['applet_ids'], true): [];
        }

        return [
            'data' => $lists,
            'total' => $total,
        ];
    }

    //抖音平台媒资短剧列表
    public function dyList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $query = ThirdVideos::alias('t')
            ->join('videos v', 't.video_id = v.id and t.platform = 2')
            ->field('t.*,v.name,v.cover_img,v.is_shelves,v.sylloge');

        if (!empty($params['name'])) $query->where('v.name','like', '%' . $params['name'] . '%');

        if (!empty($params['video_id'])) $query->where('v.id', $params['video_id']);

        if (!empty($params['album_id'])) $query->where('t.album_id', $params['album_id']);

        if (isset($params['audit_status']) && is_numeric($params['audit_status'])) {
            $video_ids = $this->getVideoIdByAuditStatus($params['audit_status']);
            if ($params['audit_status'] == 0) {
                $video_ids && $query->whereNotIn('v.id', $video_ids);
            } else {
                $video_ids ? $query->whereIn('v.id', $video_ids) : $query->where('v.id', 0);
            }
        }
        $total = $query->count();
        $order = 't.id desc';
        $lists = $query->order($order)->page($page, $limit)->select()->toArray();

        foreach ($lists as &$list) {
            $audit = VideoAuditRecords::getOneByWhere(['third_video_id' => $list['id']],'id,audit_status,online_status,updated_at','id desc');
            $status = $this->getDyAuditStatus($audit);
            $audit_status = $status['audit_status'] ?? 'none';
            $audit_at = $status['audit_at'] ?? '';
            $list['audit_status'] = $audit_status;
            $list['audit_at'] = $audit_at;
            $list['online_version'] = !empty($list['online_version']) ? (int)$list['online_version'] : 0;
        }

        return [
            'data' => $lists,
            'total' => $total,
        ];
    }

    //抖音媒资通过审核状态获得短剧id
    private function getVideoIdByAuditStatus($audit_status): array
    {
        $auditList = VideoAuditRecords::field('video_id, IFNULL(audit_status, 3) AS status')
            ->where('platform',2)
            ->order('id','desc')
            ->select()
            ->toArray();

        $videoIds = [];
        $videoData = [];
        foreach ($auditList as $item) {
            if ($audit_status == 0) {
                if (!in_array($item['video_id'], $videoIds)) {
                    $videoIds[] = $item['video_id'];
                }
            } else {
                if (!isset($videoData[$item['video_id']])) {
                    $videoData[$item['video_id']] = $item['status'];
                    if ($item['status'] == $audit_status) {
                        $videoIds[] = $item['video_id'];
                    }
                }
            }
        }
        return $videoIds;
    }

    public function thirdVideoDetail($id)
    {
        $thirdVideo = ThirdVideos::alias('t')
            ->join('videos v', 't.video_id = v.id')
            ->field('t.*,v.id as video_id,v.name,v.cover_img,v.is_shelves,v.sylloge')
            ->where('t.id', $id)
            ->find();

        if (!$thirdVideo) return [];

        switch ($thirdVideo['platform']) {
            case 2:
                $audit = VideoAuditRecords::getOneByWhere(['third_video_id' => $id],'id,audit_status,online_status,updated_at','id desc');
                $status = $this->getDyAuditStatus($audit);
                $audit_status = $status['audit_status'] ?? 'none';
                $audit_at = $status['audit_at'] ?? '';
                $thirdVideo['audit_status'] = $audit_status;
                $thirdVideo['audit_at'] = $audit_at;
                $thirdVideo['online_status'] = $audit ? $audit['online_status'] : 0;

                $config = $thirdVideo['config'] ?? [];
                $new_config = [
                    'tag_ids' => $config['tag_list'] ?? [],
                    'recommendation' => $config['recommendation'] ?? '',
                    'release_year' => $config['year'] ?? '',
                    'license_num' => $config['license_num'] ?? '',
                    'qualification' => $config['qualification'] ?? 1
                ];
                $thirdVideo['config'] = $new_config;
                break;
            default:
                break;
        }

        return $thirdVideo;
    }

    //抖音媒资审核状态
    private function getDyAuditStatus(array $audit): array
    {
        $result = ['audit_status' => 'none', 'audit_at' => ''];
        if (empty($audit)) {
            return $result;
        }

        $result['audit_status'] = 'auditing';
        if (!$audit['audit_status']) {
            return $result;
        }

        $result['audit_at'] = $audit['updated_at'];
        $result['audit_status'] = $audit['audit_status'] == 2 ? 'success' : 'fail';

        /*$audit_status = 'fail';
        if ($audit['audit_status'] == 2) {
            $is_play = EpisodeAuditRecords::where('audit_id', $audit['id'])
                ->where('audit_status','<>', 2)
                ->count();
            $audit_status = $is_play ? 'fail' : 'success';
        }*/

        return $result;
    }

    // 获取短剧下拉列表
    public function getVideoSelectList($params)
    {
        $where = [
            ['is_delete', '=', 0], ['is_copy', '=', 0], ['original_id','=', 0]
        ];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        $data = $this->videoModel->getDataByWhere($where, 'id, name');

        return $data;
    }

    //媒资短剧剧集列表
    public function viewList(array $params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'],'id,video_id,platform');
        if (!$thirdVideo) return ['data' => [], 'total' => 0];

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $platform = $thirdVideo['platform'];

        $query = VideoDetails::field('id,video_id,name,platform_config')
            ->where('video_id', $thirdVideo['video_id'])
            ->order('sort','asc');

        $total = $query->count();
        $lists = $query->page($page, $limit)->select()->toArray();

        foreach ($lists as &$list) {
            $list['platform'] = $platform;
            switch ($platform) {
                case 2:
                    $conf = $list['platform_config']['douyinyun'] ?? [];
                    $list['upload_status'] = $conf['upload_status'] ?? 0;
                    $list['binding_status'] = $conf['binding_status'] ?? 0;
                    $list['page_binding_status'] = $conf['page_binding_status'] ?? 0;
                    $list['episode_id'] = (string)($conf['episode_id'] ?? '');

                    $audit = EpisodeAuditRecords::where('video_detail_id',$list['id'])
                        ->order('id','desc')
                        ->find();
                    $audit_status = 'none';
                    if ($audit) {
                        $audit_status = $audit['audit_status'] ? ($audit['audit_status'] == 2 ? 'success' : 'fail') : 'auditing';
                    }
                    $list['audit_status'] = $audit_status;
                    break;
                default:
                    break;
            }

            unset($list['platform_config']);
        }

        return [
            'data' => $lists,
            'total' => $total,
        ];
    }

    //媒资审核列表
    public function auditList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $query = VideoAuditRecords::alias('r')
            ->join('videos v', 'r.video_id = v.id', 'left')
            ->field('r.*,v.name,v.cover_img');

        if (!empty($params['name'])) $query->where('v.name','like', '%' . $params['name'] . '%');

        if (!empty($params['video_id'])) $query->where('v.id', $params['video_id']);

        $total = $query->count();
        $lists = $query->page($page, $limit)->order('r.id','desc')->select()->toArray();

        foreach ($lists as &$list) {
            $list['audit_at'] = $list['audit_status'] ? $list['updated_at'] : '';
            $scope_list = $list['scope_list'] ? json_decode($list['scope_list'], true) : '';
            $list['scope_list'] = $scope_list ? implode('，', $scope_list) : '';
        }

        return [
            'data' => $lists,
            'total' => $total,
        ];
    }

    //媒资短剧记录审核列表
    public function auditViewList(array $params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $query = EpisodeAuditRecords::alias('e')
            ->join('video_details v', 'e.video_detail_id = v.id', 'left')
            ->field('e.id,e.version,e.audit_status,e.audit_remark,e.updated_at,v.name')
            ->where('audit_id', $params['id']);

        $total = $query->count();
        $lists = $query->page($page, $limit)->order('v.sort','asc')->select()->toArray();

        foreach ($lists as &$list) {
            $list['audit_at'] = $list['audit_status'] ? $list['updated_at'] : '';
        }

        return [
            'data' => $lists,
            'total' => $total,
        ];
    }

    /**
     * 短剧同步第三方媒体库
     * @param array $params
     * @return array|string[]
     */
    public function shortPlayThirdPartySync(array $params): array
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'],'id,album_id,platform,video_id,config');
        if (!$thirdVideo) return ['参数错误', 400];

        $video = $this->videoModel->getInfoById($thirdVideo['video_id'], 'id,name,cover_img,sylloge,synopsis');
        if (!$video) return ['参数错误', 400];

        $detail = $this->detailModel->getAllDataByVideoId($thirdVideo['video_id'],'id,video_id,url');
        $total = $video['sylloge'] ?: count($detail);
        $params['synopsis'] = $video['synopsis'] ?: '暂无';
        $params['video_id'] = $thirdVideo['video_id'];

        $config = $thirdVideo['config'] ?: [];
        $saveData['id'] = $params['id'];
        switch ($thirdVideo['platform']) {
            case 2 : //抖音
                $douyinService = new DouYinService();
                if (empty($thirdVideo['album_id'])) {   //创建
                    $result = $douyinService->saveShortPlay($video['name'], $total, $video['cover_img'], $params);
                    if ($result['msg']) return [$result['msg']];
                    $saveData['album_id'] = $result['data']['album_id'];
                } else {    //编辑
                    $douyinConf = $config;
                    $douyinConf['album_id'] = $thirdVideo['album_id'];
                    $result = $douyinService->saveShortPlay($video['name'], $total, $video['cover_img'], $params, $douyinConf);
                    if ($result['msg']) return [$result['msg']];
                }

                $saveData['config'] = $result['data']['album_info'];
                $res = ThirdVideos::update($saveData);
                break;
            default:
                return ['暂不支持'];
                break;
        }

        return $res ? [] : ['操作失败'];
    }

    //短剧剧集媒资视频上传
    public function videosThirdPartyUpload(array $params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'], 'id,video_id,platform,album_id');
        if (!$thirdVideo) return ['参数错误', 400];

        $video = $this->videoModel->getInfoById($thirdVideo['video_id'], 'id,name');
        if (!$video) return ['参数错误', 400];

        $details = $this->detailModel->getDataByWhere([
            'video_id' => $thirdVideo['video_id'],
            'id' => $params['ep_ids']
        ],'id,third_url as url,sort,platform_config');

        if (!$details) return ['参数错误', 400];

        $redis = Cache::store('redis')->handler();
        $redis->select(8);
        $redisKey = 'dy_episode_batch_upload_' . $params['id'];
        $is_exist = $redis->setnx($redisKey, 1);
        if (!$is_exist) return ['请求过快'];
        $redis->expire($redisKey, 120);

        switch ($thirdVideo['platform']) {
            case 2 : //抖音
                if (!$thirdVideo['album_id']) {
                    $redis->del($redisKey);
                    return ['请先同步短剧', 400];
                }
                $douyinService = new DouYinService();
                $result = $douyinService->uploadVideos($video['name'], $details);
                $redis->select(8);
                $redis->del($redisKey);
                if (!$result) return ['剧集上传失败'];
                return [];
            default:
                $redis->del($redisKey);
                return ['暂不支持'];
        }
    }

    //短剧绑定媒资视频
    public function videosThirdPartySync(array $params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'], 'id,video_id,platform,album_id,config');
        if (!$thirdVideo) return ['参数错误', 400];

        $video = $this->videoModel->getInfoById($thirdVideo['video_id'], 'id,name,cover_img,sylloge,synopsis');
        if (!$video) return ['参数错误', 400];

        $details = $this->detailModel->getDataByWhere([
            'video_id' => $thirdVideo['video_id'],
            'id' => $params['ep_ids']
        ],'id,name,third_url as url,sort,platform_config');

        if (!$details) return ['参数错误', 400];

        switch ($thirdVideo['platform']) {
            case 2 : //抖音
                if (!$thirdVideo['album_id']) return ['请先同步短剧', 400];
                $video['platform_config'] = $thirdVideo['config'];
                $douyinService = new DouYinService();
                $result = $douyinService->saveVideos($video, $details, $thirdVideo['album_id']);
                if ($result['msg']) return [$result['msg']];

                $res = ThirdVideos::update([
                    'id' => $thirdVideo['id'],
                    'version' => $result['data']['version']
                ]);
                break;
            default:
                return ['暂不支持'];
        }

        return $res ? [] : ['操作失败'];
    }

    //第三方送审
    public function thirdPartyAudit(array $params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'], 'id,album_id,platform,video_id');
        if (!$thirdVideo) return ['参数错误', 400];

        $details = $this->detailModel->getAllDataByVideoId($thirdVideo['video_id'],'id,platform_config');

        switch ($thirdVideo['platform']) {
            case 2 : //抖音
                if (empty($thirdVideo['album_id'])) return ['请先同步短剧及剧集'];

                $douyinService = new DouYinService();
                $result = $douyinService->audit($thirdVideo['album_id']);
                if ($result['msg']) return [$result['msg']];

                //创建送审日志
                Db::startTrans();
                try {
                    $videoRecord = VideoAuditRecords::create([
                        'third_video_id' => $thirdVideo['id'],
                        'video_id' => $thirdVideo['video_id'],
                        'platform' => 2,
                        'album_id' => $thirdVideo['album_id'],
                    ]);
                    $episodes = new EpisodeAuditRecords();
                    $episodeData = [];
                    foreach ($details as $detail) {
                        $detail_config = $detail['platform_config']['douyinyun'] ?? [];
                        if (!$detail_config || empty($detail_config['episode_id'])) continue;
                        $episodeData[] = [
                            'audit_id' => $videoRecord->id,
                            'video_id' => $thirdVideo['video_id'],
                            'video_detail_id' => $detail['id'],
                            'episode_id' => $detail_config['episode_id'],
                        ];
                    }

                    $episodeData && $episodes->saveAll($episodeData);
                    Db::commit();

                } catch (\Exception $e) {
                    Db::rollback();
                    return ['送审记录入库失败'];
                }
                return [];
            default:
                return ['暂不支持'];
        }
    }

    //送审前前置配置
    public function thirdPartyConfig(array $params)
    {
        $type = $params['type'] ?? 0;
        switch ($type) {
            case 2:
                $douyinService = new DouYinService();
                $result = $douyinService->callbackConfig();
                if ($result['msg']) return [$result['msg']];
                return [];
                break;
            default:
                echo 'dddd';
                exit();
        }

    }

    //抖音回调
    public function dyCallback(array $params)
    {
        $type = $params['type'] ?? '';
        $result = ['err_no' => 0, 'err_tips' => 'success'];
        if (empty($type)) return $result;

        $data = !empty($params['msg']) ? (is_array($params['msg']) ? $params['msg'] : json_decode($params['msg'], true)) : [];
        if (!$data) return $result;

        switch ($type) {
            case 'episode_audit':
                $videoAudit = VideoAuditRecords::getOneByWhere(['album_id' => $data['album_id'],'platform' => 2],'*','id desc');
                if (!$videoAudit) return $result;
                $episodeAudit = EpisodeAuditRecords::getOneByWhere(['episode_id' => $data['episode_id'], 'audit_id' => $videoAudit['id']]);
                if (!$episodeAudit) return $result;
                EpisodeAuditRecords::update([
                    'id' => $episodeAudit['id'],
                    'audit_status' => $data['audit_status'],
                    'version' => $data['version'],
                    'audit_remark' => $data['audit_msg'] ?? '',
                ]);

                break;
            case 'album_audit':
                $videoAudit = VideoAuditRecords::getOneByWhere(['album_id' => $data['album_id'],'platform' => 2],'*','id desc');
                if (!$videoAudit) return $result;
                VideoAuditRecords::update([
                    'id' => $videoAudit['id'],
                    'audit_status' => $data['audit_status'],
                    'version' => $data['version'],
                    'scope_list' => !empty($data['scope_list']) ? json_encode($data['scope_list'], JSON_UNESCAPED_UNICODE) : '',
                    'audit_remark' => $data['audit_msg'] ?? '',
                ]);
                ThirdVideos::update([
                    'id' => $videoAudit['third_video_id'],
                    'version' => $data['version']
                ]);
                break;
            case 'upload_video':
                break;
            default:
                return ['err_no' => 400, 'err_tips' => 'fail'];
                break;
        }

        return $result;
    }

    //第三方上线
    public function thirdPartyOnline($params)
    {
        $id = $params['id'];
        $thirdVideo = $this->thirdVideoModel->getOneById($id, 'id,album_id,platform,video_id,version');
        if (!$thirdVideo) return ['参数错误', 400];

        switch ($thirdVideo['platform']) {
            case 2: //抖音
                $online_version = $params['online_version'] ?? 0;
                $version = $thirdVideo['version'] ?: 0;
                if (!is_numeric($online_version)) return ['参数错误', 400];
                if (!$thirdVideo['album_id'] || empty($online_version) || $online_version > $version) return ['无法上线'];

                $res = (new DouYinService())->online($thirdVideo['album_id'], $online_version);
                if (!empty($res['msg'])) {
                    return [$res['msg']];
                }

                ThirdVideos::where('id', $id)->save(['online_version' => $online_version]);
                VideoAuditRecords::where(['third_video_id' => $id, 'version' => $online_version])->update(['online_status' => 1]);
                return [];
            default:
                return ['暂未开发'];
        }
        return ['无法上线'];
    }

    //短剧第三方小程序授权
    public function thirdPartyAuthorize(array $params, $type = 2)
    {
        if ($type == 1) {   //微信
            $thirdVideo = $this->thirdVideoModel->getOneByWhere([
                'video_id' => $params['video_id'],
                'platform' => 1
            ], 'id,album_id,platform,video_id,applet_ids,task_status');

            if (!$thirdVideo) {
                $video = $this->videoModel->getInfoById($params['video_id'], 'id,drama_id');
                if (!$video) return ['参数错误', 400];
                if (!$video['drama_id']) return ['无剧目id,无法授权'];
                $thirdVideo = [
                    'video_id' => $video['id'],
                    'platform' => 1,
                    'album_id' => $video['drama_id'],
                    'task_status' => 0
                ];
                $id = Db::name('third_videos')->insert($thirdVideo,true);
                if (!$id) return ['操作失败', 500];
                $thirdVideo['id'] = $id;
            }

        } else {    //抖音
            $thirdVideo = $this->thirdVideoModel->getOneById($params['id'], 'id,album_id,platform,video_id,applet_ids,task_status');
        }
        if (!$thirdVideo) return ['参数错误', 400];

        switch ($thirdVideo['platform']) {
            case 2: //抖音
                if (!$thirdVideo['album_id'] || empty($params['applet_ids'])) return ['无法授权'];
                if ($thirdVideo['task_status'] == 1) return ['授权任务还在执行中...'];

                $applet_ids = explode(',', $params['applet_ids']);
                $applets = Applet::whereIn('id', $applet_ids)->where('type',2)->column('app_id', 'id');
                if (empty($applets)) return ['无法授权'];

                $this->thirdVideoModel->where('id',$thirdVideo['id'])->update(['task_status' => 1]);

                //一部队列处理
                Queue::push('app\job\DyMediaAppletAuthorize', ['id' => $thirdVideo['id'], 'applet_ids' => $applet_ids], 'dyMediaAppletAuthorize');

                /*
                $originAppletIds = $thirdVideo['applet_ids'] ?: [];
                //获取差值
                $diffAppKeys = [];
                foreach ($applets as $aid => $appid) {
                    if (!in_array($aid, $originAppletIds)) {
                        $diffAppKeys[$aid] = $appid;
                    }
                }
                $douyinService = new DouYinService();

                //1、页面绑定
                $failApplets = $this->dyOtherPageBinding($thirdVideo, $diffAppKeys, $douyinService);
                foreach ($applets as $aid => $appid) {
                    if (isset($failApplets[$aid])) {
                        unset($applets[$aid]);
                    }
                }
                //2、小程序授权
                $app_ids = array_keys($applets);
                $app_keys = array_values(array_filter($applets));
                $res = $douyinService->shortPlayAuthorize($thirdVideo['album_id'], $app_keys);
                if (!empty($res['msg'])) {
                    return [$res['msg']];
                }

                ThirdVideos::update([
                    'id' => $thirdVideo['id'],
                    'is_authorize' => 1,
                    'applet_ids' => $app_ids
                ]);
                */
                break;
            case 1:
                if (!$thirdVideo['album_id']) return ['无法授权'];
                if ($thirdVideo['task_status'] == 1) return ['授权任务还在执行中...'];

                $this->thirdVideoModel->where('id',$thirdVideo['id'])->update(['task_status' => 1]);
                //队列处理
                Queue::push('app\job\WxMediaAppletAuthorize', ['id' => $thirdVideo['id']], 'wxMediaAppletAuthorize');

                /*
                if (empty($params['applet_ids'])) return ['请选择小程序', 400];

                $applet_ids = explode(',', $params['applet_ids']);
                $applets = Applet::whereIn('id', $applet_ids)->where('type',1)->column('app_id', 'id');
                if (empty($applets)) return ['请选择小程序', 400];

                $origin_app_ids = $thirdVideo['applet_ids'] ?? [];
                $app_ids = array_keys($applets);

                $diff = array_diff($app_ids, $origin_app_ids);
                if (empty($diff)) return [];

                $app_keys = [];
                foreach ($diff as $aid) {
                    $app_keys[] = $applets[$aid];
                }
                $app_keys = array_filter($app_keys);

                $result = (new WechatService())->shortPlayAuthorize($thirdVideo['album_id'], $app_keys);
                if (!$result) return ['操作失败'];

                $newAids = [];
                foreach ($applets as $k => $app_id) {
                    if (in_array($app_id, $result)) {
                        $newAids[] = $k;
                    }
                }

                ThirdVideos::update([
                    'id' => $thirdVideo['id'],
                    'is_authorize' => 1,
                    'applet_ids' => array_merge($origin_app_ids, $newAids)
                ]);
                */
                break;
            default:
                return ['暂未开发'];
        }
        return [];
    }

    public function batchPageBinding(array $params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'], 'id,video_id,platform,album_id,config');
        if (!$thirdVideo) return ['参数错误', 400];

        $details = $this->detailModel->getDataByWhere([
            'video_id' => $thirdVideo['video_id'],
            'id' => $params['ep_ids']
        ],'id,platform_config');

        if (!$details) return ['参数错误', 400];

        switch ($thirdVideo['platform']) {
            case 2 : //抖音
                if (!$thirdVideo['album_id']) return ['请先同步短剧', 400];
                $douyinService = new DouYinService();
                $updateData = [];
                foreach ($details as $detail) {
                    $platformConf = $detail['platform_config'] ?? [];
                    $platformConf2 = $platformConf['douyinyun'] ?? [];
                    $episode_id = $platformConf2['episode_id'] ?? '';
                    if (!$episode_id) continue;
                    $result = $douyinService->pageBanding(
                        $thirdVideo['album_id'],
                        $episode_id,
                        ['video_id' => $thirdVideo['video_id'], 'detail_id' => $detail['id']]
                    );
                    if ($result['msg']) continue;
                    $platformConf['douyinyun']['page_binding_status'] = 1;
                    $updateData[] = [
                        'id' => $detail['id'],
                        'platform_config' => $platformConf
                    ];
                }
                if ($updateData) {
                    (new VideoDetails())->saveAll($updateData);
                }
                break;
            default:
                break;
        }

        return [];
    }

    //其他小程序页面绑定
    public function dyOtherPageBinding($thirdVideo, $applets, DouYinService $douyinService): array
    {
        if (empty($applets)) return [];

        $details = $this->detailModel->getDataByWhere([
            'video_id' => $thirdVideo['video_id'],
        ],'id,platform_config');

        if (!$details) return [];

        $failApplets = [];
        foreach ($applets as $aid => $appid) {
            if ($douyinService->douyinConf['appid'] == $appid) {
                continue;
            }
            foreach ($details as $detail) {
                $platformConf = $detail['platform_config'] ?? [];
                $platformConf2 = $platformConf['douyinyun'] ?? [];
                $episode_id = $platformConf2['episode_id'] ?? '';
                if (!$episode_id) {
                    $failApplets[$aid] = $appid;
                    break;
                }

                $result = $douyinService->pageBanding(
                    $thirdVideo['album_id'],
                    $episode_id,
                    ['video_id' => $thirdVideo['video_id'], 'detail_id' => $detail['id'], 'app_id' => $appid]
                );

                if ($result['msg']) {
                    flog(['result' => $result, 'detail_id' => $detail['id'], 'app_id' => $appid],'dy_other_page_binding');
                    $failApplets[$aid] = $appid;
                    break;
                }
            }
        }
        return $failApplets;
    }

    public function dyAlbumDetailQuery($params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneById($params['id'], 'id,video_id,platform,album_id');
        if (!$thirdVideo) return ['msg' => '参数错误'];

        $params = [];
        $douyinService = new DouYinService();
        $result = $douyinService->albumDetailQuery($thirdVideo['album_id'], $params);
        if (!empty($result['msg'])) return ['msg' => $result['msg']];

        return ['msg' => '', 'data' => $result['data']];
    }

    //微信剧目授权查询
    public function wechatAuthorizeQuery($params)
    {
        $thirdVideo = $this->thirdVideoModel->getOneByWhere([
            'video_id' => $params['video_id'],
            'platform' => 1
        ], 'id,album_id,platform,video_id,applet_ids');

        if (!$thirdVideo || empty($thirdVideo['album_id'])) {
            return ['data' => [], 'total' => 0];
        }
        $result = (new WechatService())->queryAuthorize($thirdVideo['album_id'], $params);
        if (!$result) return ['data' => [], 'total' => 0];

        list($data, $total) = $result;
        $applets = Applet::where(['type' => 1])->column('name','app_id');
        foreach ($data as &$item) {
            $item['authorized_time'] = date('Y-m-d H:i:s', $item['authorized_time']);
            $item['name'] = $applets[$item['authorized_appid']] ?? '';
        }

        return [
            'data' => $data,
            'total' => $total,
        ];
    }
}